import { createRouter, createWebHistory } from "vue-router";
import HomeView from "@/views/HomeView.vue";
import DefaultLayout from "@/layouts/DefaultLayout.vue";
import LoginView from "@/views/LoginView.vue";
import AboutView from "@/views/AboutView.vue";
import ErrorView from "@/views/ErrorView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: DefaultLayout,
      meta: { requiresAuth: true },
      children: [
        {
          path: "",
          name: "home-content", // 为子路由添加独立的名称
          component: HomeView,
          meta: { keepAlive: true }
        },
      ],
    },
    {
      path: "/about",
      component: DefaultLayout,
      meta: { requiresAuth: true },
      children: [
        {
          path: "",
          name: "about-content", // 为子路由添加独立的名称
          component: AboutView,
          meta: { keepAlive: true }
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: LoginView,
      meta: { requiresAuth: false },
    },
    // 404页面 - 必须放在最后
    {
      path: "/:pathMatch(.*)*",
      name: "error",
      component: ErrorView,
    },
  ],
});

// 添加导航守卫
router.beforeEach((to, from, next) => {
  // 检查目标路由是否需要认证
  if (to.meta?.requiresAuth) {
    const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";
    if (!isLoggedIn) {
      // 如果需要认证但未登录，重定向到登录页
      localStorage.removeItem("isLoggedIn");
      next({
        name: "login",
        query: { redirect: to.fullPath },
        replace: true,
      });
    } else {
      // 其他情况允许访问
      next();
    }
  } else {
    next();
  }
});
export default router;
